package cli

import (
	"errors"
	"gitee.com/tjccc/gomq/mq/protocol"
	"math/rand"
	"net"
	"time"
)

type Producer struct {
	address string
	conn    net.Conn
	id      int32
	ackFlag bool
}

func (p Producer) Send(msg *protocol.CustomMsg) error {
	_, err := p.conn.Write(msg.ToBytes())
	return err
}

type ProducerBuilder struct {
	address string
	conn    net.Conn
	id      int32
	ackFlag bool
}

func NewProducerBuilder() *ProducerBuilder {
	return &ProducerBuilder{
		ackFlag: false,
	}
}

func (pb *ProducerBuilder) SetAckFlag(ackFlag bool) *ProducerBuilder {
	pb.ackFlag = ackFlag
	return pb
}

func (pb *ProducerBuilder) SetAddress(address string) *ProducerBuilder {
	pb.address = address
	return pb
}

func (pb *ProducerBuilder) Build() (*Producer, error) {
	if pb.address == "" {
		return nil, errors.New("address is empty")
	}

	p := &Producer{
		address: pb.address,
		ackFlag: pb.ackFlag,
	}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	p.id = r.Int31()
	return p, nil
}

func (p Producer) Start() error {
	conn, err := net.Dial("tcp", p.address)
	if err != nil {
		return err
	}
	p.conn = conn
	go tickPull(conn)
	return nil
}

func (p Producer) Shutdown() error {
	return p.conn.Close()
}
